/*
 * DFT.cpp
 * 离散傅立叶变换
 *  Created on: 2011-7-21
 *      Author: yuantao
 */

#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <iostream>
using namespace cv;
using namespace std;

void help()
{
    cout << "离散傅立叶变换" << endl;
    cout << "用法： DFT <Input Image Name> <Output Image Name>" << endl;
    cout << "示例：DFT lena.jpg lena_dft.jpg" << endl;
}


int main(int argc, char ** argv)
{
    if(argc != 3) {
        help();
        return 0;
    }
    const char * srcFileName = argv[1];
    const char * dstFileName = argv[2];

    Mat img = imread(srcFileName, CV_LOAD_IMAGE_GRAYSCALE);
    if( img.empty() )
    {
        cout << "错误：" << srcFileName << "文件不存在" << endl;
        help();
        return 0;
    }
    
    cout << "输入图像行数：" << img.rows << endl;
    cout << "输入图像列数：" << img.cols << endl;
    
    int M = getOptimalDFTSize( img.rows );
    int N = getOptimalDFTSize( img.cols );
    
    cout << "输出频谱幅度图像行数：" << img.rows << endl;
    cout << "输出频谱幅度图像列数：" << img.cols << endl;
    Mat padded;
    copyMakeBorder(img, padded, 0, M - img.rows, 0, N - img.cols, BORDER_CONSTANT, Scalar::all(0));

    Mat planes[] = {Mat_<float>(padded), Mat::zeros(padded.size(), CV_32F)};
    Mat complexImg;
    merge(planes, 2, complexImg);

    dft(complexImg, complexImg);

    cout << "对频谱幅度进行对数拉伸，便于显示" << endl;
    // compute log(1 + sqrt(Re(DFT(img))**2 + Im(DFT(img))**2))
    split(complexImg, planes);
    magnitude(planes[0], planes[1], planes[0]);
    Mat mag = planes[0];
    mag += Scalar::all(1);
    log(mag, mag);

    int cx = N/2;
    int cy = M/2;

    // rearrange the quadrants of Fourier image
    // so that the origin is at the image center
    Mat tmp;
    Mat q0(mag, Rect(0, 0, cx, cy));
    Mat q1(mag, Rect(cx, 0, cx, cy));
    Mat q2(mag, Rect(0, cy, cx, cy));
    Mat q3(mag, Rect(cx, cy, cx, cy));

    q0.copyTo(tmp);
    q3.copyTo(q0);
    tmp.copyTo(q3);

    q1.copyTo(tmp);
    q2.copyTo(q1);
    tmp.copyTo(q2);

    normalize(mag, mag, 0, 255, CV_MINMAX);

    imwrite(dstFileName, mag);
    cout << "离散傅立叶变换操作完成" << endl;
    
    return 0;
}
